package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.feign.BehaviorClient;
import com.heima.article.feign.UserClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-24
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    @Lazy
    private IPublishService publishService;

    /**
     * 保存文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //构建article对象
        ApArticle article = new ApArticle();
        //拷贝属性
        BeanUtils.copyProperties(dto, article);
        //判断是否更新
        if (dto.getId() == null) {
            //添加创建时间
            article.setCreatedTime(new Date());
            //保存文章
            this.save(article);
            //保存文章的内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            contentService.save(content);

            //生成静态的html  同样使用线程池来完成
            System.out.println(Thread.currentThread().getName() + "开始调用静态页面服务");
            //同步数据到es中
            publishService.createHtml(article,dto.getContent());

            //返回新增文章的id
            return ResponseResult.okResult(article.getId());
        }

        //更新文章
        this.updateById(article);
        //更新文章内容

        LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
        update.eq(ApArticleContent::getArticleId,dto.getId());
        update.set(ApArticleContent::getContent,dto.getContent());
        contentService.update(update);
        return ResponseResult.okResult(dto.getId());
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     *  首页加载文章
     * @param dto
     * @param type 1:最新  0:更多
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
            // 判断是否是首页
        if (dto.getLoaddir() == 1) {
            // 先从redis中查询文章列表数据 按照分值从大到小排列
            String key = "hot_article_" + dto.getChannelId();
            Set<String> setJson = redisTemplate.opsForZSet().reverseRange(key, 0, dto.getSize() - 1);
            // 如果redis中数据足够分页的size 直接返回(有可能在项目上线初期第二天出现,基本不用关心)
            List<ApArticle> articles = new ArrayList<>();
            for (String json : setJson) {
                ApArticle article = JSON.parseObject(json, ApArticle.class);
                articles.add(article);
            }
            if (articles.size() == dto.getSize()) {
                return ResponseResult.okResult(articles);
            }
            // 否则依旧从数据库查询
        }

        //分页查询
        //构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        //判断频道
        if (dto.getChannelId() != 0){
            query.eq(ApArticle::getChannelId,dto.getChannelId());
        }
        //如果是已下架或者标明已删除的文章则不被查询出来
        query.eq(ApArticle::getIsDelete,false);
        query.eq(ApArticle::getIsDown,false);
        if (type == 0 ){
            //如果加载的是更多，查询比前端传递的最小时间还早的文章
            query.lt(ApArticle::getPublishTime,dto.getMinTime());
        }else {
            //如果加载的是最新，查询比前端传递的最大时间还晚的文章
            query.gt(ApArticle::getPublishTime,dto.getMaxTime());
        }
        //按照发布时间倒序排序
        query.orderByDesc(ApArticle::getPublishTime);
        //构建分页条件
        IPage<ApArticle> page =new Page<>(1,dto.getSize());
        IPage<ApArticle> iPage = this.page(page, query);
        //给前端返回数据
        return ResponseResult.okResult(iPage.getRecords());
    }

    /**
     * 加载文章详情
     * @param dto
     * @return
     */
    @Override
    public ResponseResult info(ArticleInfoDto dto) {
        //根据文章id查询文章和文章内容
        ApArticle apArticle = this.getById(dto.getArticleId());
        //根据文章id查询内容
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent articleContent = contentService.getOne(query);
        //定义返回格式
        Map<String,Object> map = new HashMap<>();
        map.put("config",apArticle);
        map.put("content",articleContent);
        return ResponseResult.okResult(map);
    }

    @Autowired
    private IApCollectionService collectionService;

    @Value("${topic.collectBehavor}")
    private String collectTopic;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 收藏文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建ApCollection对象
        ApCollection collection = new ApCollection();
        collection.setArticleId(dto.getArticleId());
        collection.setEntryId(user.getUserId());
        collection.setCollectionTime(new Date());
        //判断是否已经有收藏记录 根据文章id和当前登录用户id查询
        LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId,dto.getArticleId());
        query.eq(ApCollection::getEntryId,user.getUserId());
        ApCollection one = collectionService.getOne(query);
        //如果没有 新增
        if (one == null){
           if (dto.getOperation() == 0){
               collectionService.save(collection);
               //发送消息到kafka
               sendMessage(dto);
           }
        }else {
            //如果存在 如果取消收藏 直接删除
            if (dto.getOperation() == 1){
                collectionService.remove(query);
                //发送消息到kafka
                sendMessage(dto);
            }
        }



        return ResponseResult.okResult();
    }

    /**
     * 加载用户行为记录
     * @param dto
     * @return
     */

    @Autowired
    private BehaviorClient behaviorClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private IApAuthorService authorService;

    @Override
    public ResponseResult loadBehavior(ArticleInfoDto dto) {
        boolean isFollow = false;
        boolean isCollection = false;
        boolean isLike = false;
        boolean isUnlike = false;

        User user = AppThreadLocalUtil.get();

        // 远程查询行为微服务 不喜欢记录

        // 查询点赞记录
        LikesBehaviorDto likeDto = new LikesBehaviorDto();
        likeDto.setEquipmentId(dto.getEquipmentId());
        if (user != null) {
            likeDto.setUserId(user.getUserId());
        }
        likeDto.setArticleId(dto.getArticleId());
        ResponseResult<ApLikesBehavior> likesBehaviorResponseResult = behaviorClient.getLikes(likeDto);
        if (likesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApLikesBehavior likesBehavior = likesBehaviorResponseResult.getData();
            if (likesBehavior != null && likesBehavior.getOperation() == 0) {
                isLike = true;
            }
        }
        // 查询不喜欢记录
        UnLikesBehaviorDto unlikeDto = new UnLikesBehaviorDto();
        BeanUtils.copyProperties(likeDto, unlikeDto);
        ResponseResult<ApUnlikesBehavior> unlikesBehaviorResponseResult = behaviorClient.getUnlikes(unlikeDto);
        if (unlikesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUnlikesBehavior unlikesBehavior = unlikesBehaviorResponseResult.getData();
            if (unlikesBehavior != null && unlikesBehavior.getType() == 0) {
                isUnlike = true;
            }
        }
        // 在文章微服务自身查询收藏记录 根据用户id和文章id查询
        if (user != null) {
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
            query.eq(ApCollection::getEntryId, user.getUserId());
            query.eq(ApCollection::getArticleId, dto.getArticleId());
            ApCollection one = collectionService.getOne(query);
            if (one != null) {
                isCollection = true;
            }
        }

        // 远程查询用户微服务的关注记录
        if (user != null) {
            FollowBehaviorDto followDto = new FollowBehaviorDto();
            followDto.setUserId(user.getUserId());
            // 根据前端传递的authorId查询作者信息,拿到作者的userId
            ApAuthor author = authorService.getById(dto.getAuthorId());
            followDto.setFollowId(author.getUserId());
            ResponseResult<ApUserFollow> followResponseResult = userClient.getFollow(followDto);
            if (followResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApUserFollow userFollow = followResponseResult.getData();
                if (userFollow != null) {
                    isFollow = true;
                }
            }
        }
        // 给前端返回固定的格式
        Map<String, Boolean> map = new HashMap<>();
        map.put("isfollow", isFollow);
        map.put("islike", isLike);
        map.put("isunlike", isUnlike);
        map.put("iscollection", isCollection);
        return ResponseResult.okResult(map);
    }
    @Override
    public void updateRedOrMy(ArticleStreamMessage articleStreamMessage) {
        Long articleId = articleStreamMessage.getArticleId();
        ApArticle byId = this.getById(articleId);
        Integer channelId = byId.getChannelId(); // 频道Id
        // 操作最终结果
        double newScore = this.newScore(articleStreamMessage); // 聚合结果的总分
        //"hot_article_"
        //Articlecache
        Articlecache articlecache = new Articlecache();
        BeanUtils.copyProperties(byId,articlecache);
        String s = JSON.toJSONString(articlecache);
        Double score = redisTemplate.opsForZSet().score("hot_article_" + channelId, s);
        if (score == null){
            //如果等于null  说明该文章在redis中不存在
            //计算该文章原来的数据 并添加当前的数据
            Double score1 = this.score(byId); // 历史分数
            double maxScore = score1 + newScore; // 最终分数
            redisTemplate.opsForZSet().add("hot_article_" + channelId,s,maxScore);
            redisTemplate.opsForZSet().add("hot_article_0",s,maxScore);
            redisTemplate.expire("hot_article_"+ channelId,23*60+58, TimeUnit.MINUTES);
            redisTemplate.expire("hot_article_0" +String.valueOf(byId.getChannelId())
                    ,23*60+58, TimeUnit.MINUTES); // 设定过期时间
        }else {
            // 数据存在 直接添加当前的数据
            redisTemplate.opsForZSet().incrementScore("hot_article_" + channelId,s,newScore);
            redisTemplate.opsForZSet().incrementScore("hot_article_0",s,newScore);
        }
        this.insertMysql(articleStreamMessage);
    }

    private void insertMysql(ArticleStreamMessage articleStreamMessage) {
        Long articleId = articleStreamMessage.getArticleId();
        LambdaUpdateWrapper<ApArticle> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ApArticle::getId,articleId);
        wrapper.setSql("likes = likes + " + articleStreamMessage.getLike());
        wrapper.setSql("views = views + " + articleStreamMessage.getView());
        wrapper.setSql("collection = collection + " + articleStreamMessage.getCollect());
        wrapper.setSql("comment = comment + " + articleStreamMessage.getComment());
        this.update(wrapper);


    }

    private Double score(ApArticle apArticle) {
        //计算分值
            Integer views = apArticle.getViews(); // 阅读数量
            Integer likes = apArticle.getLikes(); // 点赞数量
            Integer comment = apArticle.getComment(); // 评论数量
            Integer collection = apArticle.getCollection(); // 收藏数量
            double maxScore = (views * 1) + (likes * 3) + (comment * 5) + (collection * 8); //计算总分数
            return maxScore;
    }

    private double newScore(ArticleStreamMessage articleStreamMessage) {
        double like = articleStreamMessage.getLike() * 3 * 3;
        double collect = articleStreamMessage.getCollect() * 3 * 8;
        double view = articleStreamMessage.getView() * 3 * 1;
        double comment  = articleStreamMessage.getComment() * 3 * 5;
        double news = like + collect + view + comment;
        return news;
    }

    /**
     *  发送消息到kafka
     * @param dto
     */
    private void sendMessage(CollectionBehaviorDto dto) {
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(3);
        message.setArticleId(dto.getArticleId());
        message.setAdd(1);
        if (dto.getOperation() == 1){
            message.setAdd(-1);
        }
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(collectTopic,value);
    }
}

